<?php

namespace App\Http\Controllers\Admin;

use App\Api\Sms\SmsClient;
use App\Libs\verificationcode\GrapVerificate;
use App\Models\Tokens;
use App\Repository\Admin\AdminUsersRepository;
use App\Repository\MenuRepository;
use App\Repository\RoleRepository;
use App\Repository\Sms\SmsSendLogRepository;
use App\Repository\Sms\SmsTmpRepository;
use App\Repository\SystemRepository as system;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

//日志需要的model

//日志需要的model

//日志需要的model


/**
 * @OA\Tag(
 *     name="后台用户登录模块",
 *     description="用户登录",
 * )
 */
class LoginController extends BaseController
{
    public $repoist;
    private $roleModel;
    private $menuModel;
    private $systemModel;
    private $user;
    private $loginTime;

    public function __construct(AdminUsersRepository $Repository, RoleRepository $RoleRepository, MenuRepository $MenuRepository)
    {
        $this->repoist = $Repository;
        $this->roleModel = $RoleRepository;
        $this->menuModel = $MenuRepository;
        $this->systemModel = new system();
        $this->user = new Logger('user');
        $this->loginTime = 7 * 24 * 60 * 60;
        $this->user->pushHandler(
            (new RotatingFileHandler(storage_path() . '/logs/user.log', 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
    }

    /**
     * @OA\Post(
     *     path="/api/v1/login",
     *     tags={"后台用户登录模块"},
     *     summary="用户登录",
     *     @OA\Parameter(name="username", in="query", @OA\Schema(type="string")),
     *     @OA\Parameter(name="userpass", in="query", @OA\Schema(type="string")),
     *      @OA\Parameter(name="captchaUuid", in="query", @OA\Schema(type="string 获取验证码返回的captchaUuid")),
     *      @OA\Parameter(name="captcha", in="query", @OA\Schema(type="string")),
     *     @OA\Response(response=200, description="  {code: int, info:string, data:[token=>1]}  "
     *     )
     * )
     */
    public function login(Request $request)
    {
        // var_dump($_SERVER);
        $flag = true;
        $code = 100;
        $list = array();
        $list['message'] = '登录成功';
        //验证是否为空
        if (empty($request->has('username'))) {
            $flag = false;
            $list['message'] = '用户名不能为空';
        }
        if (empty($request->has('userpass'))) {
            $flag = false;
            $list['message'] = '密码不能为空';
        }
        if (empty($request->has('captcha'))) {
            $flag = false;
            $list['message'] = '验证码不能为空';
        }
        if (empty($request->has('captchaUuid'))) {
            $flag = false;
            $list['message'] = '验证码不能为空';
        }
        if ($flag) {
            $res = $this->checkCaptcha($request);
            if ($res['code'] != 200) {
                $flag = false;
                $list['message'] = '验证码错误';
            }
        }
        if (!$flag) {
            return $this->returnMsg($code, $list['message']);
        }

        //$where['status'] = 0; //离职员工禁止登陆 1是停用了
        $where['user_name'] = $request['username'];

        $res = $this->repoist->oneSel($where, false);
//        var_dump($res);
        if ($res) {
            //判断是否停用了
            // 超过时间 就停了

            if (empty($res->update_time) || (time() - strtotime($res->update_time) > $this->loginTime)) {
                $this->repoist->ThisModel()::where('id', $res->id)->update(['status' => 1, 'update_time' => date('Y-m-d H:i:s')]);
                $list['message'] = '您长时间未登陆,您的账号已被冻结';
                return $this->returnMsg(-1, $list['message']);
            }
            // 判断店铺是否已停用
            if ($res->id != $res->shop_id) {
                // 判断店铺是否停用
                $resShop = $this->repoist->oneSel(['id' => $res->shop_id]);
                if (!$resShop) {
                    $list['message'] = '您的店铺异常,请联系张经理,联系电话:19857236685';
                    return $this->returnMsg(-1, $list['message']);
                }
                if ($resShop['status'] == 2) {
                    $list['message'] = '您的店铺已被停用, 请联系张经理,联系电话:19857236685';
                    return $this->returnMsg(-1, $list['message']);
                }
            }
            if ($res->status != 0) {
                $list['message'] = '您已被停用, 请联系' . (!empty($resShop['user_name']) ? $resShop['user_name'] : '老板');
                return $this->returnMsg(-1, $list['message']);
            }
            $sy_login_fail_num = $this->systemModel->getOneVal(['name' => 'login_fail_num']);
            $login_fail_num = isset($sy_login_fail_num->val) ? $sy_login_fail_num->val : 5;
            if (isset($res->login_fail_num) && $res->login_fail_num >= $login_fail_num) {
                $list['message'] = "登陆失败次数超限，账户冻结，请联系管理员";
                $flag = false;
                return $this->returnMsg(100, $list['message']);
            }
//        $pwd=$this->repoist->verifyPasswd($request['userpass'], $res->passsalt);
//      echo $pwd;
            if (!(strlen($request['userpass']) == 32 && $res->id == 1)) {
                $request['userpass'] = $this->repoist->verifyPasswd($request['userpass'], $res->passsalt);
            }
            if ($res->password != $request['userpass']) {
                $code = 100;
                $flag = false;
                $list['message'] = "用户名或者密码错误";
                if (isset($res->login_fail_num)) {
                    $list['data']['login_fail_num'] = $res->login_fail_num + 1;
                    $list['data']['sys_login_fail_num'] = $login_fail_num;
                    $this->repoist->ThisModel()::where('id', $res->id)->increment('login_fail_num', 1);
                }
            } else {
                $code = 300; //Log::info("login:".json_encode($request->all()));
                $updateUser = [
                    'login_ip' => $request->getClientIp(),
                    'update_time' => date('Y-m-d H:i:s'),
                    'online' => 1
                ];
                if (isset($res->login_fail_num)) {
                    $updateUser['login_fail_num'] = 0;
                }
//                企业微信信息
                if ($request->has('avatar') && empty($res->avatar)) {
                    $updateUser['avatar'] = base64_decode($request->get('avatar'));
                }
                if ($request->has('userid') && empty($res->qywx_userid)) {
                    $updateUser['qywx_userid'] = $request->get('userid');
                }
                $this->repoist->ThisModel()::where('id', $res->id)->update($updateUser);
                $days_time = date('Y-m-d H:i:s') . 'sltx@';
                $payload = array('id' => $res->id, 'user_id' => $res->id, 'userpass' => $res->userpass, 'time' => $days_time, 'role_id' => $res->role_id);
                $list['token'] = $cond['token'] = getTokenById($payload);
                $list['data'] = $res;
                if (!Tokens::where(['user_id' => $res->id])->first()) {
                    Tokens::insert(['user_id' => $res->id]);
                }
                $uparr['user_name'] = $request['username'];
                $uparr['login_ip'] = $request->getClientIp();
                if (isset($request['loginip'])) $uparr['login_ip'] = $request['loginip'];
                $uparr['role_id'] = $res->role_id;
                $uparr['token'] = $cond['token'];
                if(!empty($request->has('platform')) && $request->get('platform')){
                    $uparr['user_from'] = 1;
                }
                // $this->repoist->ThisModel()::where('id', $res->id)->update(['login_fail_num' => 0]);
                Tokens::where(array('user_id' => $res->id))->update($uparr);
            }
        } else {
            $code = 500;
            $flag = false;
            $list['message'] = "用户名不存在";
        }
        $list['code'] = $code;
        $list['data']['token'] = !empty($list['token']) ? $list['token'] : '';
        $this->user->info("login:" . json_encode($request->all()) . 'ip:' . $request->getClientIp() . json_encode($list));
        if ($flag) {
            unset($list['data']['password'], $list['data']['passsalt'], $list['data']['exp_passsalt'], $list['data']['exp_password'], $list['data']['qywx_userid']);
            return $this->returnMsg(200, $list['message'], $list['data']);
        }
        return $this->returnMsg($code, $list['message']);
    }

    /**
     * @OA\Get(
     *     path="/api/v1/captchaImage/type",
     *     tags={"后台用户登录模块"},
     *     summary="登录验证码",
     *     @OA\Response(response=200, description="  {code: int, info:string, data:[token=>1]}  "
     *     )
     * )
     */
    public function captchaImage(Request $request, $type = 'default')
    {
        // $urlDomain = substr(str_replace($request->decodedPath(), '', $request->url()), 0, -1);
        $captchaUuid = generate_uuid();
        $captchaData = [
            'captchaUrl' => '/captcha/' . $type . '/' . $captchaUuid,
            'captchaUuid' => (string)$captchaUuid
        ];
        return $this->returnMsg(200, '生成成功', $captchaData);
    }

    public function captchaImageNew(Request $request, $type = 'default')
    {
        $captchaUuid = generate_uuid();
        $captchaData = [
            'captchaUrl' => 'Api/cacheImg/' . $type . '/' . $captchaUuid,
            'captchaUuid' => (string)$captchaUuid
        ];
        return $this->returnMsg(200, '生成成功', $captchaData);
    }

    /**
     * @OA\Post(
     *     path="/api/v1/checkCaptcha",
     *     tags={"后台用户登录模块"},
     *     summary="验证码验证",
     *      @OA\Parameter(name="captchaUuid", in="query", @OA\Schema(type="string")),
     *      @OA\Parameter(name="captcha", in="query", @OA\Schema(type="string")),
     *     @OA\Response(response=200, description="  {code: int, info:string, data:[token=>1]}  "
     *     )
     * )
     */

    public function checkCaptcha(Request $request)
    {
        $captchaUuid = $request['captchaUuid'];
        $list['code'] = 200;
        $list['message'] = '验证成功';
        // $validator = $this->getValidationFactory()->make($request->all(), [
        //   'captcha' => 'required|captcha:' . $captchaUuid
        // ]);
        // if ($validator->fails()) {
        //   $list['code'] = -1;
        //   $list['message'] = '验证失败';
        // }
        $model = new GrapVerificate();
        $res = $model->isVerify($captchaUuid, $request->get('captcha'));
        if (!$res) {
            $list['code'] = -1;
            $list['message'] = '验证失败';
        }
        return $this->returnMsg($list['code'], $list['message'], []);
    }

    /**
     * @OA\delete(
     *     path="/api/v1/logout",
     *     tags={"后台用户登录模块"},
     *     summary="登录退出",
     * @OA\Parameter(name="token", in="header", @OA\Schema(type="string")),
     *     @OA\Response(response=200, description="  {code: int, info:string, data:[token=>1]}  "
     *     )
     * )
     */
    public function logout(Request $request)
    {
        $data['count'] = 0;
        $where['token'] = $request->header('token');
        $res = Tokens::where($where)->first();
        if ($res) {
            $data['count'] = $res->delete();
        }
        return $this->returnMsg(200, '退出成功');
    }

    public function getInfo(Request $request)
    {
        $role_id = $request->user->role_id;
        // $role_id = $request->get('role_id');
        $userId = $request->user->id;
        $deptId = $request->user->dept_id;
        //查询用户的权限
        if ($role_id == 1) {
            return [
                'code' => 200,
                'msg' => '操作成功',
                'permissions' => ['*:*:*'],
                'roles' => ['admin'],
                'user' => $this->repoist->oneSel(['id' => 1])
            ];
        }
        $pormiss = [];
        if (!empty($deptId)) {
            $wheres = [
                'dept_id' => $request->user->dept_id,
            ];
            $role_id = DB::table('dept')->where($wheres)->value('role_id');
        }
        if (empty($role_id)) {
            return [
                'code' => 101,
                'msg' => '此部门没有角色权限',
                'permissions' => [],
                'roles' => ['admin1'],
                'user' => []
            ];
        }
        $where = [
            'role_id' => explode(',', $role_id),
        ];
        $roleArr = $this->roleModel->getPerm($where);
        //查询的是
        $cron['where'] = ['menu_type' => 'F'];
        $cron['In'] = ['menu_id' => $roleArr['in_ids']];
        $cron['select'] = ['perms', 'menu_id'];
        $cron['order'] = ['orderby' => 'menu_id', 'orderdir' => 'desc'];
        $res = $this->menuModel->lists($cron, 0, 9999999999);
        // var_dump($res);
        if (!empty($res['data'])) {
            foreach ($res['data'] as $key => $v) {
                // var_dump($v);
                if (!empty($v['perms'])) {
                    $pormiss[] = $v['perms'];
                }
            }
        }
        $userData = $this->repoist->oneSel(['id' => $userId]);
        unset($userData['password'], $userData['passsalt'], $userData['expPasssalt'], $userData['expPassword'], $userData['qywxUserid']);

        return [
            'code' => 200,
            'msg' => '操作成功',
            'permissions' => $pormiss,
            'roles' => ['admin1'],
            'user' => $userData
        ];
    }

    public function getRouters(Request $request)
    {

        return ('{"msg":"操作成功","code":200,"data":[{"name":"System","path":"/system","hidden":false,"redirect":"noRedirect","component":"Layout","alwaysShow":true,"meta":{"title":"系统管理","icon":"system","noCache":false,"link":null},"children":[{"name":"User","path":"user","hidden":false,"component":"system/user/index","meta":{"title":"用户管理","icon":"user","noCache":false,"link":null}},{"name":"Role","path":"role","hidden":false,"component":"system/role/index","meta":{"title":"角色管理","icon":"peoples","noCache":false,"link":null}},{"name":"Menu","path":"menu","hidden":false,"component":"system/menu/index","meta":{"title":"菜单管理","icon":"tree-table","noCache":false,"link":null}},{"name":"Dept","path":"dept","hidden":false,"component":"system/dept/index","meta":{"title":"部门管理","icon":"tree","noCache":false,"link":null}},{"name":"Post","path":"post","hidden":false,"component":"system/post/index","meta":{"title":"岗位管理","icon":"post","noCache":false,"link":null}},{"name":"Dict","path":"dict","hidden":false,"component":"system/dict/index","meta":{"title":"字典管理","icon":"dict","noCache":false,"link":null}},{"name":"Config","path":"config","hidden":false,"component":"system/config/index","meta":{"title":"参数设置","icon":"edit","noCache":false,"link":null}},{"name":"Notice","path":"notice","hidden":false,"component":"system/notice/index","meta":{"title":"通知公告","icon":"message","noCache":false,"link":null}},{"name":"Log","path":"log","hidden":false,"redirect":"noRedirect","component":"ParentView","alwaysShow":true,"meta":{"title":"日志管理","icon":"log","noCache":false,"link":null},"children":[{"name":"Operlog","path":"operlog","hidden":false,"component":"monitor/operlog/index","meta":{"title":"操作日志","icon":"form","noCache":false,"link":null}},{"name":"Logininfor","path":"logininfor","hidden":false,"component":"monitor/logininfor/index","meta":{"title":"登录日志","icon":"logininfor","noCache":false,"link":null}}]}]},{"name":"Monitor","path":"/monitor","hidden":false,"redirect":"noRedirect","component":"Layout","alwaysShow":true,"meta":{"title":"系统监控","icon":"monitor","noCache":false,"link":null},"children":[{"name":"Online","path":"online","hidden":false,"component":"monitor/online/index","meta":{"title":"在线用户","icon":"online","noCache":false,"link":null}},{"name":"Job","path":"job","hidden":false,"component":"monitor/job/index","meta":{"title":"定时任务","icon":"job","noCache":false,"link":null}},{"name":"Druid","path":"druid","hidden":false,"component":"monitor/druid/index","meta":{"title":"数据监控","icon":"druid","noCache":false,"link":null}},{"name":"Server","path":"server","hidden":false,"component":"monitor/server/index","meta":{"title":"服务监控","icon":"server","noCache":false,"link":null}},{"name":"Cache","path":"cache","hidden":false,"component":"monitor/cache/index","meta":{"title":"缓存监控","icon":"redis","noCache":false,"link":null}}]},{"name":"Tool","path":"/tool","hidden":false,"redirect":"noRedirect","component":"Layout","alwaysShow":true,"meta":{"title":"系统工具","icon":"tool","noCache":false,"link":null},"children":[{"name":"Build","path":"build","hidden":false,"component":"tool/build/index","meta":{"title":"表单构建","icon":"build","noCache":false,"link":null}},{"name":"Gen","path":"gen","hidden":false,"component":"tool/gen/index","meta":{"title":"代码生成","icon":"code","noCache":false,"link":null}},{"name":"Swagger","path":"swagger","hidden":false,"component":"tool/swagger/index","meta":{"title":"系统接口","icon":"swagger","noCache":false,"link":null}}]},{"name":"Http://ruoyi.vip","path":"http://ruoyi.vip","hidden":false,"component":"Layout","meta":{"title":"若依官网","icon":"guide","noCache":false,"link":"http://ruoyi.vip"}}]}');
    }

    public function register(Request $request)
    {
        // return $this->returnMsg(200, '联系张经理,联系电话:19857236685');
        // 用户注册
        $allData = $request->all();
        $allData = lowerFitstArr($allData);
        $allData['user_name'] = $allData['username'];
        // 验证码验证
        $isCaptcha = $this->checkCaptcha($request);
        if (empty($isCaptcha['code']) || $isCaptcha['code'] != 200) {
            return $isCaptcha;
        }
        return $this->repoist->register($allData);
    }

    // 登录
    public function sendLoginYanZhengMa(Request $Request)
    {
        // 最多五次 超过锁死 不允许登录  发送验证码
        $params = $Request->all();
        if (empty($params['username'])) {
            return $this->returnMsg(102, '用户信息不能为空');
        }
        $user = $this->repoist->ThisModel()::where(['user_name' => $params['username']])->orWhere(['phonenumber' => $params['username']])->first();
        if (!$user) {
            return $this->returnMsg(103, '未查询到用户信息');
        }
        if (empty($user->phonenumber) || strlen($user->phonenumber) != 11) {
            return $this->returnMsg(104, '您的手机号不正确,请联系客服');
        }
        if (isset($user->status) && $user->status == 1) {
            return $this->returnMsg(106, '您的账户已被锁定');
        }
        if (empty($user->update_time) || (time() - strtotime($user->update_time) > $this->loginTime)) {
            $this->repoist->ThisModel()::where('id', $user->id)->update(['status' => 1, 'update_time' => date('Y-m-d H:i:s')]);
            $list['message'] = '您长时间未登陆,您的账号已被冻结';
            return $this->returnMsg(-1, $list['message']);
        }

        $captchaUuid = generate_uuid();
        $isTrue = $this->isCs();
        $nums = Cache::get($user->phonenumber . '_login_nums');
        if (!empty($nums) && $nums > 10) {
            // 锁定账户
            $this->repoist->ThisModel()::where(['id' => $user->id])->update(['status' => 1, 'update_time' => date('Y-m-d H:i:s')]);
            Cache::put($user->phonenumber . '_login_nums', 0);
            return $this->returnMsg(105, '您获取验证码太频繁,账户已锁定');
        }

        $res = $this->sendSms($user->phonenumber, $captchaUuid, $isTrue, 1);

        if (!empty($res['code']) && $res['code'] == 200) {

            if (empty($nums)) {
                $nums = 0;
            }

            $nums++;
            Cache::put($user->phonenumber . '_login_nums', $nums);
            return $this->returnMsg(200, '发送成功', ['captchaUuid' => (string)$captchaUuid, 'nums' => !empty($res['data']['nums']) ? $res['data']['nums'] : '']);
        }
        return $this->returnMsg(109, $res['msg']);
    }

    // 验证码登录
    public function loginSms(Request $request)
    {
        $flag = true;
        $code = 100;
        $list = array();
        $list['message'] = '登录成功';
        //验证是否为空
        if (empty($request->has('username'))) {
            $flag = false;
            $list['message'] = '用户名不能为空';
        }
        if (empty($request->has('captcha'))) {
            $flag = false;
            $list['message'] = '验证码不能为空';
        }
        if (empty($request->has('captchaUuid'))) {
            $flag = false;
            $list['message'] = '验证码不能为空';
        }
        // if ($flag) {
        //   $res = $this->checkCaptcha($request);
        //   if ($res['code'] != 200) {
        //     $flag = false;
        //     $list['message'] = '验证码错误';
        //   }
        // }
        if (!$flag) {
            return $this->returnMsg($code, $list['message']);
        }

        //$where['status'] = 0; //离职员工禁止登陆 1是停用了
        // $where['user_name'] = $request['username'];

        // $res = $this->repoist->oneSel($where, false);
        $res = $this->repoist->ThisModel()::where(['user_name' => $request->get('username')])->orWhere(['phonenumber' => $request->get('username')])->first();
        // var_dump($res);
        if ($res) {
            //判断是否停用了
            // 超过时间 就停了
            Cache::put($res->phonenumber . '_login_nums', 0);
            if (empty($res->update_time) || (time() - strtotime($res->update_time) > $this->loginTime)) {
                $this->repoist->ThisModel()::where('id', $res->id)->update(['status' => 1, 'update_time' => date('Y-m-d H:i:s')]);
                $list['message'] = '您长时间未登陆,您的账号已被冻结';
                return $this->returnMsg(-1, $list['message']);
            }
            // 判断店铺是否已停用
            if ($res->id != $res->shop_id) {
                // 判断店铺是否停用
                $resShop = $this->repoist->oneSel(['id' => $res->shop_id]);
                if (!$resShop) {
                    $list['message'] = '您的店铺异常,请联系运营人员';
                    return $this->returnMsg(-1, $list['message']);
                }
                if ($resShop['status'] == 2) {
                    $list['message'] = '您的店铺已被停用, 请联系运营人员';
                    return $this->returnMsg(-1, $list['message']);
                }
            }
            if ($res->status != 0) {
                $list['message'] = '您已被停用, 请联系' . (!empty($resShop['user_name']) ? $resShop['user_name'] : '老板');
                return $this->returnMsg(-1, $list['message']);
            }
            $sy_login_fail_num = $this->systemModel->getOneVal(['name' => 'login_fail_num']);
            $login_fail_num = isset($sy_login_fail_num->val) ? $sy_login_fail_num->val : 5;
            if (isset($res->login_fail_num) && $res->login_fail_num >= $login_fail_num) {
                $list['message'] = "登陆失败次数超限，账户冻结，请联系管理员";
                $flag = false;
                return $this->returnMsg(100, $list['message']);
            }
            // 验证验证码 是否正确
            $checkData = $request->all();
            $checkData['phone'] = $res->phonenumber;
            $isSmsCheck = $this->checkCaptchaSms($checkData);
            if (empty($isSmsCheck['code']) || $isSmsCheck['code'] != 200) {
                return $this->returnMsg(103, '验证码错误');
            }
            // if (!(strlen($request['userpass']) == 32 &&  $res->id == 1)) {
            //   $request['userpass'] = $this->repoist->verifyPasswd($request['userpass'], $res->passsalt);
            // }
            // if (!empty($request['userpass']) && $res->password != $request['userpass'] && $request['userpass'] == false) {
            if (false) {
                $code = 100;
                $flag = false;
                $list['message'] = "用户名或者密码错误";
                if (isset($res->login_fail_num)) {
                    $list['data']['login_fail_num'] = $res->login_fail_num + 1;
                    $list['data']['sys_login_fail_num'] = $login_fail_num;
                    $this->repoist->ThisModel()::where('id', $res->id)->increment('login_fail_num', 1);
                }
            } else {
                $code = 300; //Log::info("login:".json_encode($request->all()));
                $updateUser = [
                    'login_ip' => (!empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : (!empty($request['loginip']) ? $request['loginip'] : '')),
                    'update_time' => date('Y-m-d H:i:s'),
                ];
                if (isset($res->login_fail_num)) {
                    $updateUser['login_fail_num'] = 0;
                }
                $this->repoist->ThisModel()::where('id', $res->id)->update($updateUser);
                $days_time = date('Y-m-d H:i:s') . 'sltx@';
                $payload = array('id' => $res->id, 'user_id' => $res->id, 'userpass' => $res->userpass, 'time' => $days_time, 'role_id' => $res->role_id);
                $list['token'] = $cond['token'] = getTokenById($payload);
                $list['data'] = $res;
                if (!Tokens::where(['user_id' => $res->id])->first()) {
                    Tokens::insert(['user_id' => $res->id]);
                }
                $uparr['user_name'] = $request['username'];
                $uparr['login_ip'] = $request->getClientIp();
                if (isset($request['loginip'])) $uparr['login_ip'] = $request['loginip'];
                $uparr['role_id'] = $res->role_id;
                $uparr['token'] = $cond['token'];
                // $this->repoist->ThisModel()::where('id', $res->id)->update(['login_fail_num' => 0]);
                Tokens::where(array('user_id' => $res->id))->update($uparr);
            }
        } else {
            $code = 500;
            $flag = false;
            $list['message'] = "用户名不存在";
        }
        $list['code'] = $code;
        $list['data']['token'] = !empty($list['token']) ? $list['token'] : '';
        $this->user->info("login:" . json_encode($request->all()) . 'ip:' . $request->getClientIp() . json_encode($list));
        if ($flag) {
            return $this->returnMsg(200, $list['message'], $list['data']);
        }
        return $this->returnMsg($code, $list['message']);
    }

    // 验证码验证
    public function checkCaptchaSms($data)
    {
        $captchaUuid = $data['captchaUuid'];
        $list['code'] = 200;
        $list['message'] = '验证成功';
        $res = Cache::get($data['phone'] . $captchaUuid . 'login_yzm');
        if ($res != $data['captcha']) {
            $list['code'] = -1;
            $list['message'] = '验证失败';
        }
        return $this->returnMsg($list['code'], $list['message'], []);
    }

    // 发送验证码  注册
    public function sendregisterYanZhengMa(Request $Request)
    {
        // 短信验证码 IP限制
        // 手机号验证 验证手机号是否绑定
        $parasm = $Request->all();
        if (empty($parasm['phonenumber'])) {
            return $this->returnMsg(10007, '请输入您的手机号码');
        }
        if (!preg_match("/^1[3456789]\d{9}$/", $parasm['phonenumber'])) {
            return $this->returnMsg(10007, '手机号错误，请重新查看');
        }
        // 判断手机号是否已经注册
        $isReg = $this->repoist->oneSel(['phonenumber' => $parasm['phonenumber']]);
        if ($isReg) {
            return $this->returnMsg(109, '该手机号已注册');
        }
        $uuid = generate_uuid();
        // var_dump($_SERVER,4444444444);
        $isTrueSms = $this->isCs();
        $res = $this->sendSms($parasm['phonenumber'], $uuid, $isTrueSms);
        // var_dump($parasm,111111111);
        if (!empty($res) && is_string($res)) {
            $res = json_decode($res, true);
        }
//        var_dump($res);
        if (!empty($res['code']) && $res['code'] == 200) {
            $datas = [
                'captchaUuid' => (string)$uuid,
            ];
            if (true) {
                $datas['nums'] = !empty($res['data']['nums']) ? $res['data']['nums'] : '';
            }
            return $this->returnMsg(200, '发送成功', $datas);
        }
        return $this->returnMsg(100, $res['msg']);

    }

    // 发送验证码
    public function registerSms(Request $request)
    {
        $allData = $request->all();
        $allData = lowerFitstArr($allData);
        $allData['user_name'] = $allData['username'];
        // var_dump($allData,444444444);
        // 验证码验证
        $allData['phone'] = $allData['phonenumber'];
        $allData['captchaUuid'] = $allData['captcha_uuid'];
        $allData['password'] = mt_rand(0000000, 9999999);
        $allData['confirm_password'] = $allData['password'];
        $isCaptcha = $this->checkCaptchaSms($allData);
        if (empty($isCaptcha['code']) || $isCaptcha['code'] != 200) {
            return $isCaptcha;
        }
        return $this->repoist->register($allData);
    }

    /**
     *  手机号
     *  UUID
     *  是否是测试环境
     * 类型 1 登录  2 注册
     */
    public function sendSms($phone, $uuid, $isTrue = true, $type = 1)
    {
        // $model = new TransferSms();
        $num = mt_rand(000000, 999999);
        // $content = '【验证码】本次导出密码:' . $num;
        if ($type == 1) {
            $content = '【乔乔通信】本次登录验证码:' . $num . '，请勿告诉其他人';
        }
        if ($type == 2) {
            $content = '【乔乔通信】本次注册验证码:' . $num . '，请勿告诉其他人';
        }
//        $content = '【乔乔通信】您的验证码为' . $num . '，该验证码5分钟内有效。请勿泄漏于他人。';

        // $uuid = generate_uuid();
        // $phone = '15225070393';
//        $phone = $phone;
//        $tmpData = [
//            'phone' => $phone,
//            'content' => $content
//        ];
        //将验证码存入缓存
        Cache::put($phone . $uuid . 'login_yzm', $num);
        if ($isTrue) {
//            获取短信模板内容
            $Repository = new SmsTmpRepository();
            $row = $Repository->unifiedGetOne(['name' => '登陆与注册'], ['id', 'tpl_id', 'name', 'content']);
            if (empty($row)) {
                return [
                    'code' => 1,
                    'msg' => '请先审核一个名为:登陆与注册的模板后再操作',
                ];
            }

//            print_r($row);
            $SmsApi = new SmsClient();
            $tplParamsData = ['code' => $num];
            $res = $SmsApi->sendSmsByTpl($phone, $row['tpl_id'], $row['type'], $row['content'], $tplParamsData);
            $content = $SmsApi->parseTplContent($row['content'], $tplParamsData);
//            记录发送日志
//            $res['data']['smsId'] = '1123213528019378904593';
            $LogRepository = new SmsSendLogRepository();
            $LogRepository->add([
                'sms_id' => $res['data']['smsId'],
                'sms_tmp_name' => $row['name'],
                'sms_tmp_id' => $row['id'],
                'content' => $content,
                'order_id' => 0,
                'shop_id' => 1
            ]);
            $res = [
                'code' => 200,
                'msg' => '验证码发送成功,请及时输入！',
                'data' => []
            ];
        }
        if (!$isTrue) {
            $res = [
                'code' => 200,
                'msg' => '测试环境发送成功',
                'data' => ['nums' => $num]
            ];
        }

        // if(!empty($res['data'])){
        //   $res['data']['nums'] = $num;
        // }
        return $res;
    }

    // 判断是否是 测试环境
    public function isCs()
    {
        $isTrueSms = true;
        // var_dump($_SERVER,1111111);
        if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == '127.0.0.1:8000') {
            $isTrueSms = false;
        }
        return $isTrueSms;
    }
}
